import React, { useMemo, useCallback, useState, useEffect } from 'react';
import { Button } from 'antd';
import { history as router } from 'umi';
import _config from '../_config';

const { controlConfig } = _config;
const renderOpt = (text, opts) => {
  if (text === undefined || text === null) return null;
  if (Array.isArray(opts) && opts.length > 0) {
    return opts.find(item => item?.value === text)?.label;
  }
  return null;
};

export default function useInitColumns({ status }) {
  const [controlOptions, setControlOptions] = useState(null);
  useEffect(() => {
    const promises = Object.entries(controlConfig).map(([key, val]) => ({
      key,
      options: val.options,
    }));
    if (!Promise.allSettled) {
      // 当浏览器不支持
      const rejectHandler = reason => ({ status: 'rejected', reason });
      const resolveHandler = value => ({ status: 'fulfilled', value });
      Promise.allSettled = promises =>
        Promise.all(
          promises.map(promise => Promise.resolve(promise).then(resolveHandler, rejectHandler)),
          // 每个 promise 需要用 Promise.resolve 包裹下
          // 以防传递非 promise
        );
    }
    Promise.allSettled(promises.map(v => v.options)).then(res => {
      const v = {};
      res.forEach((d, idx) => {
        if (d.status === 'rejected') {
          console.error(
            d.reason || new Error(`Failed to get options for field "${promises[idx].key}"`),
          );
        }
        v[promises[idx].key] = d.status === 'fulfilled' ? d.value : undefined;
      });
      setControlOptions(v);
    });
  }, []);

  const memoCol = useMemo(
    () =>
      [
        {
          title: '序号',
          dataIndex: '__index',
          key: '__index',
          width: 60,
          align: 'center',
        },
        {
          title: '下拉',
          dataIndex: '下拉',
          width: 120,
          render: text => renderOpt(text, controlOptions?.keywords_options),
        },
      ].filter(Boolean),
    [controlOptions, status],
  );

  const gotoDetail = useCallback(
    ({ __index, ...record }) => {
      router.push({
        pathname: '/detail',
        query: {
          ...record,
          approvalStatus: status,
        },
      });
    },
    [status],
  );

  const columns = useMemo(
    () => [
      ...memoCol,
      {
        title: '操作',
        dataIndex: 'action',
        align: 'center',
        fixed: 'right',
        width: status !== '2' ? 150 : 100,
        render: (text, record) => (
          <div style={{ display: 'flex', justifyContent: 'center' }}>
            <Button type="link" onClick={() => gotoDetail(record)}>
              详情
            </Button>
          </div>
        ),
      },
    ],
    [memoCol, gotoDetail],
  );

  return columns;
}
